package cn.com.jdyun.service.impl;

import cn.com.jdyun.exception.BdexGatewayException;
import cn.com.jdyun.mapper.PartnerIncomeMapper;
import cn.com.jdyun.mapper.UserCandyMapper;
import cn.com.jdyun.mapper.ext.ExtSysConfigMapper;
import cn.com.jdyun.mapper.ext.ExtUserWalletMapper;
import cn.com.jdyun.pojo.LockCoin;
import cn.com.jdyun.pojo.PartnerIncome;
import cn.com.jdyun.pojo.SysConfig;
import cn.com.jdyun.pojo.User;
import cn.com.jdyun.pojo.UserCandy;
import cn.com.jdyun.pojo.UserWallet;
import cn.com.jdyun.pojo.Withdraw;
import cn.com.jdyun.service.ExchangeService;
import cn.com.jdyun.service.LockCoinService;
import cn.com.jdyun.service.MessageService;
import cn.com.jdyun.service.SysConfigService;
import cn.com.jdyun.service.TransferService;
import cn.com.jdyun.service.UserSecService;
import cn.com.jdyun.service.UserWalletService;
import cn.com.jdyun.util.ConfigParam;
import cn.com.jdyun.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserWalletServiceImpl implements UserWalletService {

    @Autowired
    private ExtUserWalletMapper userWalletMapper;
    @Autowired
    private LockCoinService lockCoinService;
    @Autowired
    private PartnerIncomeMapper partnerIncomeMapper;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserCandyMapper userCandyMapper;
    @Autowired
    private TransferService transferService;
    @Autowired
    private UserWalletService userWalletService;
    @Autowired
    private ExchangeService exchangeService;
    @Autowired
    private ExtSysConfigMapper sysConfigMapper;
    @Autowired
    private UserSecService userSecService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserWallet createWallet(String userId, String coinType, String amount) throws BdexGatewayException {
        UserWallet wallet = queryByUserIdAndConiType(userId, coinType);
        if (wallet != null) {
            return wallet;
        }
        wallet = new UserWallet();
        wallet.setUserId(userId);
        wallet.setCoinType(coinType);
        if (StringUtils.isBlank(amount)) {
            amount = "0";
        }
        wallet.setBalance(amount);
        wallet.setFreezeCoin("0");
        wallet.setMingCoin("0");
        wallet.setTaskCoin("0");
        wallet.setAsset(amount);
        wallet.setLockedCoin(new BigDecimal("0"));
        Date cur = new Date();
        wallet.setCreateTime(cur);
        wallet.setUpdateTime(cur);
        userWalletMapper.insertSelective(wallet);
        return wallet;
    }

    @Transactional(readOnly = true)
    @Override
    public PartnerIncome inqueryByUserId(String userId, String date) {
        return partnerIncomeMapper.inqueryByUserId(userId, date);
    }


    @Transactional(readOnly = true)
    @Override
    public UserWallet queryByUserIdAndConiType(String userId, String coinType) {
        return userWalletMapper.queryByUserIdAndConiType(userId, coinType);
    }

    @Transactional(readOnly = true)
    @Override
    public UserWallet selectByPrimaryKey(String userId) {
        return userWalletMapper.selectByPrimaryKey(Integer.valueOf(userId));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateWallet(UserWallet wallet) throws BdexGatewayException {
        if (wallet.getId() == null) {
            return;
        }
        int result = userWalletMapper.updateByPrimaryKeySelective(wallet);
        wallet.setUpdateTime(new Date());
        if (result <= 0) {
            throw new BdexGatewayException("更新比特宝失败!");
        }
    }

    @Transactional(readOnly = true)
    @Override
    public List<UserWallet> findSuperNodes(String coinType, BigDecimal amount) throws BdexGatewayException {
        List<UserWallet> userWalletList = userWalletMapper.findSuperNodes(coinType, amount);
        if (userWalletList == null || userWalletList.size() == 0) {
            throw new BdexGatewayException("没查询到比特宝信息!");
        }
        return userWalletList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Withdraw withdraw(String userId, String amount, String coinType, String fee, HttpSession session) throws BdexGatewayException {
//		UserWallet wallet = queryByUserIdAndConiType(userId, coinType);
//		//计算实际提币数量：总额-费用
//		BigDecimal real = new BigDecimal(amount).subtract(new BigDecimal(fee));
//		//判断数额大于0
//		if(real.compareTo(BigDecimal.valueOf(0)) <= 0) {
//			return null;
//		}
//		if(wallet != null) {
//			BigDecimal bAmount = new BigDecimal("amount");
//			//判断余额是否充足
//			if(bAmount.compareTo(BigDecimal.valueOf(0)) <= 0) {
//				return null;
//			}
//			if(new BigDecimal(fee).compareTo(BigDecimal.valueOf(0)) > 0) {
//				//向系统账户转一笔：费用
//				transferService.transferFrom(userId, Constant.mainAccountId, coinType, fee,secPassword,session);
//			}
//			Date cur = new Date();
//			//保存钱包余额
//			BigDecimal balance = new BigDecimal(wallet.getBalance()).subtract(bAmount);
//			wallet.setBalance(balance.toString());
//			wallet.setUpdateTime(cur);
//			userWalletMapper.updateByPrimaryKeySelective(wallet);
//
//			//保存充值记录
//			Withdraw record = new Withdraw();
//			record.setCoinAmount(real.toString());
//			record.setCoinType(coinType);
//			record.setCreateTime(cur);
//			record.setUpdateTime(cur);
//			record.setFlag(Byte.valueOf("0"));
//			record.setUserId(userId);
//			withdrawMapper.insert(record);
//			return record;
//		}
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserWallet updateSignInReward(String userId, String coinType, String reward) throws BdexGatewayException {
        UserWallet wallet = queryByUserIdAndConiType(userId, coinType);
        BigDecimal real = new BigDecimal(reward);
        //判断数额大于0
        if (real.compareTo(BigDecimal.valueOf(0)) <= 0) {
            return wallet;
        }
        if (wallet == null) {
            //若未创建钱包，则直接创建钱包
            wallet = createWallet(userId, coinType, "0");
        }
        BigDecimal taskCoin = new BigDecimal(wallet.getTaskCoin()).add(real);
        wallet.setTaskCoin(taskCoin.toString());
        wallet.setUpdateTime(new Date());
        userWalletMapper.updateByPrimaryKeySelective(wallet);
        return wallet;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserWallet updateMiningReward(String userId, String coinType, String reward) throws BdexGatewayException {
        UserWallet wallet = queryByUserIdAndConiType(userId, coinType);
        BigDecimal real = new BigDecimal(reward);
        //累加挖矿所得
        BigDecimal miningCoin = new BigDecimal(wallet.getMingCoin()).setScale(6, BigDecimal.ROUND_HALF_DOWN).add(real.setScale(6, BigDecimal.ROUND_HALF_DOWN)).setScale(6, BigDecimal.ROUND_HALF_DOWN);
        //挖矿所得直接进入可用余额
        BigDecimal balance = new BigDecimal(wallet.getBalance()).setScale(6, BigDecimal.ROUND_HALF_DOWN).add(real.setScale(6, BigDecimal.ROUND_HALF_DOWN)).setScale(6, BigDecimal.ROUND_HALF_DOWN);
        //修改总资产
        BigDecimal asset = balance.add(wallet.getLockedCoin());
//        BigDecimal asset = wallet.getLockedCoin().add(new BigDecimal(wallet.getBalance())).add(new BigDecimal(wallet.getMingCoin()));
        wallet.setMingCoin(miningCoin.toString());
        wallet.setBalance(balance.toString());
        wallet.setAsset(asset.toString());
        wallet.setUpdateTime(new Date());
        userWalletMapper.updateByPrimaryKeySelective(wallet);
        return wallet;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public LockCoin presentCoin(String userId, String amount, String coinType, boolean isInvite) throws BdexGatewayException {
        UserWallet wallet = queryByUserIdAndConiType(userId, coinType);
        BigDecimal bAmount = new BigDecimal(amount);
        //判断数额大于0
        if (bAmount.compareTo(BigDecimal.valueOf(0)) <= 0) {
            return null;
        }
        Date cur = new Date();
        if (wallet == null) {
            //若未创建钱包，则直接创建钱包
            wallet = createWallet(userId, coinType, "0");
        }

        //赠送的币直接进入锁仓状态
        BigDecimal lockedCoin = wallet.getLockedCoin().add(bAmount);
        BigDecimal asset = lockedCoin.add(new BigDecimal(wallet.getBalance())).add(new BigDecimal(wallet.getFreezeCoin()));
        wallet.setAsset(asset.toString());
        wallet.setLockedCoin(lockedCoin);
        wallet.setUpdateTime(cur);
        userWalletMapper.updateByPrimaryKeySelective(wallet);

        //如果是糖果
        if (coinType.equals(Constant.CANDY)) {
            UserCandy uc = userCandyMapper.queryByUserId(userId);
            if (uc == null) {
                uc = new UserCandy();
                uc.setUserId(userId);
                uc.setFreeAll(BigDecimal.valueOf(0));
                uc.setRewardAll(BigDecimal.valueOf(0));
                uc.setFreeInviteAll(BigDecimal.valueOf(0));
                uc.setRewardInviteAll(BigDecimal.valueOf(0));
                uc.setCreateTime(cur);
            }
            //设置获得总糖果数
            uc.setRewardAll(uc.getRewardAll().add(bAmount));
            if (isInvite) {
                //设置邀请获得的总糖果数
                uc.setRewardInviteAll(uc.getRewardInviteAll().add(bAmount));
            }
            uc.setUpdateTime(cur);
            if (uc.getId() == null) {
                userCandyMapper.insert(uc);
            } else {
                userCandyMapper.updateByPrimaryKeySelective(uc);
            }
        }

        //新增一条锁仓记录
        LockCoin lockCoin = new LockCoin();
        lockCoin.setCoinType(coinType);
        lockCoin.setInitLockCoinAmount(bAmount);
        lockCoin.setLockCoinAmount(bAmount);
        lockCoin.setSequenceId(System.currentTimeMillis() + "");
        lockCoin.setUserId(userId);
        lockCoin.setCreateTime(cur);
        lockCoin.setUpdateTime(cur);
        lockCoinService.addNewLockCoinRecode(lockCoin);

        //新增一条发送收益消息
        messageService.insertUserMessage(userId, "赠送奖励", "您有一笔新的奖励已经转至锁仓", amount, coinType,"1");
        return lockCoin;
    }

    @Transactional(readOnly = true)
    @Override
    public List<UserWallet> findLockedCoinWallet(String coinType) throws BdexGatewayException {
        return userWalletMapper.findLockedCoinWallet(coinType);
    }


    @Transactional(readOnly = true)
    @Override
    public Boolean queryStrongAmount(String userId, String coinType, BigDecimal strongLockCoinNum) {
        UserWallet userWallet = new UserWallet();
        userWallet.setUserId(userId);
        userWallet.setCoinType(coinType);
        userWallet.setLockedCoin(strongLockCoinNum);
        int result = userWalletMapper.queryStrongAmount(userWallet);
        if (result >= 3) {
            return true;
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateWalletCoinAmount(UserWallet userWallet) throws BdexGatewayException {
        int result = userWalletMapper.updateWalletCoinAmount(userWallet);
        if (result <= 0) {
            throw new BdexGatewayException("更新比特宝信息失败!");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void releaseCoinTypeRefereeReward(User user, BigDecimal refereeReward, String date) throws BdexGatewayException {
        //查看推荐人id
        String refereeId = user.getId();
        BigDecimal bAmount;
        //查询一级推荐人比特宝信息
        UserWallet refereeWallet = transferService.inqueryLockedCoinAmount(refereeId, Constant.COINTYPE_SSSP);
        //推荐人锁仓
        BigDecimal lockedCoinReferee = refereeWallet.getLockedCoin();
        if (lockedCoinReferee.compareTo(BigDecimal.valueOf(1000)) >= 0) {
            //推荐人的余额
            String refereeBalance = refereeWallet.getBalance();
            //推荐人作为合伙人收益
            BigDecimal refereePartnerProfit = new BigDecimal("0");
            //查询推荐人的作为合伙人收益
            PartnerIncome partnerIncome = userWalletService.inqueryByUserId(refereeId, date);
            if (partnerIncome != null) {
                refereePartnerProfit = partnerIncome.getAmount();
            }
            //合伙人收益加上奖励是否超过锁仓
            if (lockedCoinReferee.compareTo(refereePartnerProfit.add(refereeReward)) < 0) {
                if (lockedCoinReferee.compareTo(refereePartnerProfit) < 0) {
                    throw new BdexGatewayException("后台数据错误!");
                }
                refereeReward = lockedCoinReferee.subtract(refereePartnerProfit).setScale(6, BigDecimal.ROUND_HALF_DOWN);
            }
            bAmount = refereeReward.multiply(new BigDecimal("1")).setScale(6, BigDecimal.ROUND_HALF_DOWN);
//            refereeBalance = new BigDecimal(refereeBalance).add(bAmount).setScale(6, BigDecimal.ROUND_HALF_DOWN) + "";
            refereeWallet.setAsset(new BigDecimal(refereeWallet.getAsset()).add(refereeReward).setScale(6, BigDecimal.ROUND_HALF_DOWN) + "");

            //新增一条锁仓记录
            LockCoin lockCoin = new LockCoin();
            lockCoin.setCoinType(Constant.COINTYPE_SSSP);
            lockCoin.setInitLockCoinAmount(bAmount);
            lockCoin.setLockCoinAmount(bAmount);
            lockCoin.setSequenceId(System.currentTimeMillis() + "");
            lockCoin.setUserId(refereeId);
            lockCoin.setCreateTime(new Date());
            lockCoin.setUpdateTime(new Date());
            lockCoinService.addNewLockCoinRecode(lockCoin);

            //更新推荐人比特宝中可用额度，总资产
            refereeWallet.setLockedCoin(bAmount.add(lockedCoinReferee));
            refereeWallet.setUpdateTime(new Date());
            userWalletService.updateWalletCoinAmount(refereeWallet);

            //新增一笔用户的推荐人收益
            lockCoinService.addNewRefereeIncome(refereeId, new SimpleDateFormat("yyyy-MM-dd").format(new DateTime().minusDays(1).toDate()), bAmount, new BigDecimal("0"), Constant.COINTYPE_SSSP);
            //修改矿池
            sysConfigService.changeConfigValue(ConfigParam.MINER_POOL_AMOUNT, bAmount.multiply(BigDecimal.valueOf(-1)).toString(), refereeId);

            //新增一条发送收益消息
//            messageService.insertUserMessage(refereeId, "推荐人奖励", "您有一笔新的奖励已经转至可用余额", bAmount.toString(), Constant.COINTYPE_SSSP);
            messageService.insertUserMessage(refereeId, "推荐人奖励", "您有一笔新的奖励已经转至锁仓", bAmount.toString(), Constant.COINTYPE_SSSP,"1");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void releaseSSPRefereeReward(User referee, BigDecimal lockAmount,String coinType) throws BdexGatewayException {
        SysConfig releaseRefereeAvailableBalanceConfig = sysConfigMapper.selectByCode(Constant.releaseRefereeAvailableBalance);
        SysConfig texReleaseRefereeAvailableBalanceConfig = sysConfigMapper.selectByCode(Constant.texReleaseRefereeAvailableBalance);
        if (lockAmount == null || lockAmount.doubleValue() <= 0) {
            return;
        }
        String refereeId = referee.getId();
        //推荐人释放将要锁仓的ssp的10%【如果锁仓总的小于等于10%分量则释放全部】
        BigDecimal refereeNumCount = new BigDecimal("0");
        if(Constant.COINTYPE_SSSP.equals(coinType)){
            refereeNumCount = new BigDecimal(releaseRefereeAvailableBalanceConfig.getInitValue()).multiply(lockAmount).setScale(6, BigDecimal.ROUND_HALF_DOWN);
        }else if(Constant.COINTYPE_TEX.equals(coinType)){
            refereeNumCount = new BigDecimal(texReleaseRefereeAvailableBalanceConfig.getInitValue()).multiply(lockAmount).setScale(6, BigDecimal.ROUND_HALF_DOWN);
        }else{
            throw new BdexGatewayException("代币种类错误!");
        }
        //可以释放的总额
        BigDecimal enabledAmount = lockCoinService.queryUserEnableUnlockedAmount(refereeId, coinType);
        //释放SSP量
        BigDecimal releaseSSSPNum = new BigDecimal("0");
        //释放糖果量
        BigDecimal releaseCandyNum = new BigDecimal("0");
        //如果SSP够释放，则释放，不够释放，则计算糖果释放量
        if (enabledAmount.compareTo(refereeNumCount) < 0) {
            releaseCandyNum = refereeNumCount.subtract(enabledAmount);
            releaseSSSPNum = enabledAmount;
        } else {
            releaseSSSPNum = refereeNumCount;
        }
        //释放SSP
        if (releaseSSSPNum.doubleValue() > 0) {
            //新增一条发送释放锁仓消息
            messageService.insertUserMessage(refereeId, "推荐人锁仓" + coinType + "的释放", "您锁仓释放" + coinType + ":", releaseSSSPNum.toString(), coinType,"1");
            //更新钱包
            UserWallet wallet = userWalletMapper.inqueryLockedCoinAmount(refereeId, coinType);
            wallet.setBalance(new BigDecimal(wallet.getBalance()).add(releaseSSSPNum).toString());
            wallet.setLockedCoin(wallet.getLockedCoin().subtract(releaseSSSPNum));
            updateWallet(wallet);
            List<LockCoin> lockList = lockCoinService.queryUserEnableUnlockedCoin(refereeId, coinType);
            //逐笔释放锁仓
            for (LockCoin lc : lockList) {
                //如果释放量大于当前锁仓，则全部释放，如果小于，则释放当前可释放量
                if (releaseSSSPNum.compareTo(lc.getLockCoinAmount()) > 0) {
                    lockCoinService.releaseLockCoin(refereeId, lc.getId(), lc.getLockCoinAmount(), lc.getLockCoinAmount(), coinType, Byte.valueOf("0"));
                    releaseSSSPNum = releaseSSSPNum.subtract(lc.getLockCoinAmount());
                } else {
                    lockCoinService.releaseLockCoin(refereeId, lc.getId(), lc.getLockCoinAmount(), releaseSSSPNum, coinType, Byte.valueOf("0"));
                    break;
                }
            }
        }
        //释放CANDY
        if (releaseCandyNum.doubleValue() > 0) {
            UserWallet candyWallet = userWalletMapper.inqueryLockedCoinAmount(refereeId, Constant.CANDY);
            if(candyWallet.getLockedCoin()==null ||candyWallet.getLockedCoin().doubleValue()<=0.5){
                return;
            }
            freeCandyCoin(candyWallet, releaseCandyNum.toString(),coinType);
        }
    }

//    /**
//     * 释放用户锁仓，如果是SSSP，SSSP不足则释放糖果
//     * @param refereeId 用户id
//     * @param refereeNum 释放总数
//     * @param coinType 币种类型
//     * @throws BdexGatewayException
//     */
//    private void updateWallet(String refereeId, BigDecimal refereeNum, String coinType) throws BdexGatewayException {
//        //推荐人比特宝
//        UserWallet userWallet = userWalletMapper.inqueryLockedCoinAmount(refereeId, coinType);
//        BigDecimal refereeNumReference = refereeNum;
//        //余额
//        BigDecimal balance = new BigDecimal(userWallet.getBalance());
//        //锁仓
//        BigDecimal lockTotal = userWallet.getLockedCoin();
//        //是否需要释放糖果
//        Boolean isNeedRefereeCandy = false;
//        //释放糖果量
//        BigDecimal refereeCandyNum = new BigDecimal("0");
//        //是否需要释放糖果
//        Boolean isNeedRefereeCandy = false;
//        //释放糖果量
//        BigDecimal refereeCandyNum = new BigDecimal("0");
//        //可以释放的总额
//        BigDecimal enabledAmount = lockCoinService.queryUserEnableUnlockedAmount(refereeId, coinType);
//        //是否需要释放糖果
//        Boolean isNeedRefereeCandy = false;
//        //释放糖果量
//        BigDecimal refereeCandyNum = new BigDecimal("0");
//        //判断一级推荐人锁仓额度大于1000若是糖果则放行
//        if (coinType.equalsIgnoreCase(Constant.CANDY) || lockTotal.compareTo(new BigDecimal(Constant.tinyMiningLowestLockCoinNum)) >= 0) {
//            //查询用户锁仓记录
//            //TODO 30天释放
//            List<LockCoin> lockList = lockCoinService.selectUserLockCoin(userWallet.getUserId(), coinType);
//            if (lockList != null && lockList.size() > 0) {
//                if (lockTotal.compareTo(refereeNum) >= 0) {
//                    for (LockCoin lock : lockList) {
//                        while (refereeNumReference.intValue() != 0) {
//                            if (lock.getLockCoinAmount().compareTo(refereeNumReference) >= 0) {
//                                //新增锁仓释放记录
//                                LockCoinReleaseLog lcrl = new LockCoinReleaseLog();
//                                lcrl.setAmount(refereeNumReference);
//                                lcrl.setCoinType(coinType);
//                                lcrl.setCreateTime(new Date());
//                                lcrl.setLockCoinId(lock.getId());
//                                lcrl.setReleaseType(new Byte("0"));
//                                lcrl.setLockedCoin(lock.getLockCoinAmount());
//                                lcrl.setUserId(refereeId);
//                                lockCoinService.insertIntoReleaseLog(lcrl);
//
//                                lock.setLockCoinAmount(lock.getLockCoinAmount().subtract(refereeNumReference).setScale(6, BigDecimal.ROUND_HALF_DOWN));
//                                //更新锁仓记录
//                                lockCoinService.updateByPrimaryKeySelective(lock);
//                                refereeNumReference = new BigDecimal(0);
//                                break;
//                            } else {
//                                //新增锁仓释放记录
//                                LockCoinReleaseLog lcrl = new LockCoinReleaseLog();
//                                lcrl.setAmount(lock.getLockCoinAmount());
//                                lcrl.setCoinType(coinType);
//                                lcrl.setCreateTime(new Date());
//                                lcrl.setLockCoinId(lock.getId());
//                                lcrl.setReleaseType(new Byte("0"));
//                                lcrl.setLockedCoin(lock.getLockCoinAmount());
//                                lcrl.setUserId(refereeId);
//                                lockCoinService.insertIntoReleaseLog(lcrl);
//                                //释放完锁仓中的sssp
//                                refereeNumReference = refereeNumReference.subtract(lock.getLockCoinAmount()).setScale(6, BigDecimal.ROUND_HALF_DOWN);
//                                lock.setLockCoinAmount(new BigDecimal(0));
//                                //更新锁仓记录
//                                lockCoinService.updateByPrimaryKeySelective(lock);
//                            }
//                        }
//                    }
//                    if (coinType.equalsIgnoreCase(Constant.CANDY)) {
//                        candyTosssp(coinType, refereeId, refereeNum);
//                    } else {
//                        userWallet.setBalance(balance.add(refereeNum).setScale(6, BigDecimal.ROUND_HALF_DOWN) + "");
//                    }
//                    userWallet.setLockedCoin(lockTotal.subtract(refereeNum).setScale(6, BigDecimal.ROUND_HALF_DOWN));
//                } else {
//                    for (LockCoin lock : lockList) {
//                        //新增锁仓释放记录
//                        LockCoinReleaseLog lcrl = new LockCoinReleaseLog();
//                        lcrl.setAmount(lock.getLockCoinAmount());
//                        lcrl.setCoinType(coinType);
//                        lcrl.setCreateTime(new Date());
//                        lcrl.setLockCoinId(lock.getId());
//                        lcrl.setReleaseType(new Byte("0"));
//                        lcrl.setLockedCoin(lock.getLockCoinAmount());
//                        lcrl.setUserId(refereeId);
//                        lockCoinService.insertIntoReleaseLog(lcrl);
//                        //释放完锁仓中糖果
//                        lock.setLockCoinAmount(new BigDecimal(0));
//                        //更新锁仓记录
//                        lockCoinService.updateByPrimaryKeySelective(lock);
//                    }
//                    isNeedRefereeCandy = true;
//                    refereeCandyNum = refereeNum.subtract(lockTotal);
//                    refereeNum = lockTotal;
//                    if (coinType.equalsIgnoreCase(Constant.CANDY)) {
//                        candyTosssp(coinType, refereeId, refereeNum);
//                    } else {
//                        userWallet.setBalance(balance.add(refereeNum).setScale(6, BigDecimal.ROUND_HALF_DOWN) + "");
//                    }
//                    userWallet.setLockedCoin(new BigDecimal("0"));
//                }
//                userWallet.setUpdateTime(new Date());
//                //更新推荐人比特宝
//                int result = userWalletMapper.updateWalletCoinAmount(userWallet);
//                if (result <= 0) {
//                    throw new BdexGatewayException("更新钱包失败!");
//                }
//                if (coinType.equalsIgnoreCase(Constant.COINTYPE_SSSP) && refereeNum.intValue() > 0) {
//                    //新增一条发送释放锁仓消息
//                    messageService.insertUserMessage(refereeId, "推荐人锁仓" + coinType + "的释放", "您锁仓释放" + coinType + ":", refereeNum.toString(), Constant.COINTYPE_SSSP);
//                } else {
//                    //新增一条释放candy锁仓消息
//                    messageService.insertUserMessage(refereeId, "推荐人锁仓candy释放", "释放candy:", refereeNum.toString(), Constant.CANDY);
//                }
//                //释放糖果
//                if (isNeedRefereeCandy) {
//                    if (coinType.equalsIgnoreCase(Constant.COINTYPE_SSSP)) {
//                        //是否实名认证过
//                        UserSec userSec = userSecService.queryByUserId(refereeId);
//                        if (userSec == null || userSec.getFlag() != 1) {
//                            if (userSec == null || userSec.getFlag() != 1) {
//                                if (userSec == null || userSec.getFlag() != 2) {
//                                    return;
//                                }
//                                //如果代币锁仓量小于释放量时，释放糖果锁仓
//                                updateWallet(refereeId, refereeCandyNum, Constant.CANDY);
//                            }
//                        }
//                    }
//                }
//            }
//        }
//    }
//    private void candyTosssp(String coinType, String refereeId, BigDecimal refereeNum) throws BdexGatewayException {
//        //新增一笔用户的推荐人收益
//        lockCoinService.addNewRefereeIncome(refereeId, new SimpleDateFormat("yyyy-MM-dd").format(new DateTime().toDate()), refereeNum, new BigDecimal("0"), Constant.COINTYPE_SSSP);
//        //推荐人比特宝【sssp增加锁仓增加总资产】
//        UserWallet userWallet1 = userWalletMapper.inqueryLockedCoinAmount(refereeId, coinType);
//        userWallet1.setAsset(new BigDecimal(userWallet1.getAsset()).add(refereeNum) + "");
//        userWallet1.setLockedCoin(userWallet1.getLockedCoin().add(refereeNum));
//        userWallet1.setUpdateTime(new Date());
//        //新增一条锁仓记录
//        LockCoin lockCoin = new LockCoin();
//        lockCoin.setCoinType(Constant.COINTYPE_SSSP);
//        lockCoin.setInitLockCoinAmount(refereeNum);
//        lockCoin.setLockCoinAmount(refereeNum);
//        lockCoin.setSequenceId(System.currentTimeMillis() + "");
//        lockCoin.setUserId(refereeId);
//        lockCoin.setCreateTime(new Date());
//        lockCoin.setUpdateTime(new Date());
//        lockCoinService.addNewLockCoinRecode(lockCoin);
//        //更新推荐人比特宝
//        int result1 = userWalletMapper.updateWalletCoinAmount(userWallet1);
//        if (result1 <= 0) {
//            throw new BdexGatewayException("更新钱包失败!");
//        }
//        //修改矿池
//        sysConfigService.changeConfigValue(ConfigParam.MINER_POOL_AMOUNT, refereeNum.multiply(BigDecimal.valueOf(-1)).toString(), refereeId);
//    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void lockSSPReward(UserWallet wallet, BigDecimal lockAmount, BigDecimal giftAmount,String coinType) throws BdexGatewayException {
        //更新用户自己的比特宝
        BigDecimal lockedCoinAmount = wallet.getLockedCoin();
        lockedCoinAmount = lockedCoinAmount.add(giftAmount.add(lockAmount)).setScale(6, BigDecimal.ROUND_HALF_DOWN).setScale(6, BigDecimal.ROUND_HALF_DOWN);
        //可用余额扣除
        BigDecimal userBalanceOfTex = new BigDecimal(wallet.getBalance()).subtract(lockAmount).setScale(6, BigDecimal.ROUND_HALF_DOWN);
        BigDecimal assetNum = new BigDecimal(wallet.getAsset()).add(giftAmount).setScale(6, BigDecimal.ROUND_HALF_DOWN);
        wallet.setLockedCoin(lockedCoinAmount);
        wallet.setAsset(assetNum + "");
        wallet.setBalance(userBalanceOfTex + "");
        wallet.setUpdateTime(new Date());
        int result = userWalletMapper.updateWalletCoinAmount(wallet);
        if (result <= 0) {
            throw new BdexGatewayException("更新用户比特宝失败!");
        }
        //每天释放千分之五到可用sssp数量中
        BigDecimal curLockAmount = giftAmount.add(lockAmount);
        LockCoin lockCoinEntity = new LockCoin(
                wallet.getUserId(),
                curLockAmount,
                curLockAmount,
                coinType,
                System.currentTimeMillis() + "",
                new Date(),
                new Date()
        );
        //增加一条锁仓记录
        lockCoinService.addNewLockCoinRecode(lockCoinEntity);
        if(Constant.COINTYPE_SSSP.equals(coinType)){
            //修改矿池
            sysConfigService.changeConfigValue(ConfigParam.MINER_POOL_AMOUNT, giftAmount.multiply(BigDecimal.valueOf(-1)).toString(), wallet.getUserId());
        }else if(Constant.COINTYPE_TEX.equals(coinType)){
            //修改矿池
            sysConfigService.changeConfigValue(ConfigParam.MINER_POOL_AMOUNT_TEX, giftAmount.multiply(BigDecimal.valueOf(-1)).toString(), wallet.getUserId());
        }else{
            throw new BdexGatewayException("代币类型错误!");
        }
        //新增一条发送锁仓消息
        messageService.insertUserMessage(wallet.getUserId(), "锁仓"+coinType, "您的锁仓"+coinType+"有一笔划入", lockAmount.toString(), coinType,"0");
        //新增一条发送奖励消息
        messageService.insertUserMessage(wallet.getUserId(), "获取锁仓"+coinType+"的奖励", "您的锁仓获取了一笔额外的锁仓奖励", giftAmount.toString(), coinType,"1");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void releaseCoinTypeReward(UserWallet userWallet, BigDecimal releaseCoinNum, LockCoin lockCoin) throws BdexGatewayException {
        //用户ID
        String userId = userWallet.getUserId();
        //获取用户的可用余额
        String availBalance = userWallet.getBalance();
        BigDecimal lockedCoinNum = userWallet.getLockedCoin();
        if (lockedCoinNum.compareTo(releaseCoinNum) <= 0) {
            lockedCoinNum = new BigDecimal(0);
            //增加后的可用余额
            availBalance = "" + new BigDecimal(availBalance).add(lockedCoinNum).setScale(6, BigDecimal.ROUND_HALF_DOWN);
        } else {
            //增加后的可用余额
            availBalance = "" + new BigDecimal(availBalance).add(releaseCoinNum).setScale(6, BigDecimal.ROUND_HALF_DOWN);
            //钱包中锁仓代币也得减少
            lockedCoinNum = lockedCoinNum.subtract(releaseCoinNum);
        }
        //更新比特宝
        userWallet.setBalance(availBalance);
        userWallet.setLockedCoin(lockedCoinNum);
        userWallet.setUpdateTime(new Date());
        userWalletService.updateWalletCoinAmount(userWallet);
        if(userWallet.getCoinType().equals(Constant.COINTYPE_SSSP)){
            lockCoinService.releaseLockCoin(userId, lockCoin.getId(), lockCoin.getLockCoinAmount(), releaseCoinNum, Constant.COINTYPE_SSSP, Byte.valueOf("1"));
        }else{
            lockCoinService.releaseLockCoin(userId, lockCoin.getId(), lockCoin.getLockCoinAmount(), releaseCoinNum, Constant.COINTYPE_TEX, Byte.valueOf("1"));
        }
        //新增一条发送锁仓释放消息
        if(userWallet.getCoinType().equals(Constant.COINTYPE_SSSP)){
            messageService.insertUserMessage(userId, "锁仓释放", "锁仓额度释放到可用额度", releaseCoinNum.toString(), Constant.COINTYPE_SSSP,"1");
        }else{
            messageService.insertUserMessage(userId, "锁仓释放", "锁仓额度释放到可用额度", releaseCoinNum.toString(), Constant.COINTYPE_TEX,"1");
        }
    }

    @Transactional(readOnly = true)
    @Override
    public List<UserWallet> queryUserWallets(String userId) throws BdexGatewayException {
        return userWalletMapper.queryUserWallets(userId);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePartnerIncome(String userId, BigDecimal curUserIncome, String cointype, String date) throws BdexGatewayException {
        UserWallet userWallet = new UserWallet();
        //修改矿池
        if(Constant.COINTYPE_SSSP.equals(cointype)){
            sysConfigService.changeConfigValue(ConfigParam.MINER_POOL_AMOUNT, curUserIncome.multiply(BigDecimal.valueOf(-1)).toString(), userId);
            userWallet = queryByUserIdAndConiType(userId, Constant.COINTYPE_SSSP);
        }else if(Constant.COINTYPE_TEX.equals(cointype)){
            sysConfigService.changeConfigValue(ConfigParam.MINER_POOL_AMOUNT_TEX, curUserIncome.multiply(BigDecimal.valueOf(-1)).toString(), userId);
            userWallet = queryByUserIdAndConiType(userId, Constant.COINTYPE_TEX);
        }
        //挖矿所得直接进入可用余额
        BigDecimal balance = new BigDecimal(userWallet.getBalance()).add(curUserIncome);
        //修改总资产
        BigDecimal asset = new BigDecimal(userWallet.getAsset()).add(curUserIncome);
        userWallet.setBalance(balance.toString());
        userWallet.setAsset(asset.toString());
        userWallet.setUpdateTime(new Date());
        userWalletMapper.updateByPrimaryKeySelective(userWallet);

        //新增一条挖矿收益记录
        PartnerIncome income = new PartnerIncome();
        income.setUserId(userId);
        income.setAmount(curUserIncome);
        income.setCreateTime(new Date());
        income.setDate(date);
        income.setCoinType(cointype);
        partnerIncomeMapper.insert(income);

        //新增一条发送收益消息
        if(Constant.COINTYPE_TEX.equals(cointype)){
            messageService.insertUserMessage(userId, "超级节点/合伙人奖励", "您有一笔新的奖励已经转至可用余额", curUserIncome.toString(), Constant.COINTYPE_TEX,"1");
        }else if(Constant.COINTYPE_SSSP.equals(cointype)){
            messageService.insertUserMessage(userId, "超级节点/合伙人奖励", "您有一笔新的奖励已经转至可用余额", curUserIncome.toString(), Constant.COINTYPE_SSSP,"1");
        }


    }

    @Transactional(readOnly = true)
    @Override
    public UserCandy queryUserCandyInfo(String userId) throws BdexGatewayException {
        return userCandyMapper.queryByUserId(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void freeCandyCoin(UserWallet wallet, String amount,String coinType) throws BdexGatewayException {

        if (wallet == null || !wallet.getCoinType().equals(Constant.CANDY)) {
            throw new BdexGatewayException("请传入用户的糖果钱包");
        }

        BigDecimal locked = wallet.getLockedCoin();
        BigDecimal diff = new BigDecimal(amount);

        //如果锁仓大于释放量，则按释放量算，如果锁仓小于释放量，则全部释放
        if (locked.compareTo(diff) < 0) {
            diff = locked;
        }

        //糖果释放，直接进入转换为系统币的可用余额
        exchangeService.exchangeCandyToSSSP(wallet.getUserId(), diff,coinType, true);

        List<LockCoin> lockCoinList = lockCoinService.selectUserLockCoin1(wallet.getUserId(), Constant.CANDY);
        if (lockCoinList != null && lockCoinList.size() != 0) {
            BigDecimal leaf = diff;
            for (LockCoin lockCoin : lockCoinList) {
                if (lockCoin.getLockCoinAmount().subtract(leaf).doubleValue() < 0) {
                    diff = lockCoin.getLockCoinAmount();
                    leaf = leaf.subtract(diff);
                    lockCoinService.releaseLockCoin(lockCoin.getUserId(), lockCoin.getId(), lockCoin.getLockCoinAmount(), diff, Constant.CANDY, Byte.valueOf("0"));
                } else {
                    diff = leaf;
                    leaf = BigDecimal.valueOf(0);
                    lockCoinService.releaseLockCoin(lockCoin.getUserId(), lockCoin.getId(), lockCoin.getLockCoinAmount(), diff, Constant.CANDY, Byte.valueOf("0"));
                }
                //更新糖果释放的汇总表
                UserCandy uc = userCandyMapper.queryByUserId(lockCoin.getUserId());
                if (uc != null) {
                    uc.setFreeAll(uc.getFreeAll().add(diff));
                    //如果是邀请所得，则更新邀请所得糖果的释放量
                    SysConfig inviteCandyConfig = sysConfigMapper.selectByCode(Constant.INVITE_CANDY);
                    BigDecimal invest = new BigDecimal(inviteCandyConfig.getInitValue());
                    if (lockCoin.getInitLockCoinAmount().compareTo(invest) == 0) {
                        uc.setFreeInviteAll(uc.getFreeInviteAll().add(diff));
                    }
                    uc.setUpdateTime(new Date());
                    userCandyMapper.updateByPrimaryKeySelective(uc);
                }
                if (leaf.doubleValue() == 0) {
                    break;
                }
            }
        }
    }

    @Transactional(readOnly = true)
    @Override
    public int queryRankByAmountAndConiType(BigDecimal amount, String cointype) throws BdexGatewayException {
        return userWalletMapper.queryRankByAmountAndConiType(amount, cointype);
    }

    @Transactional(readOnly = true)
    @Override
    public List<UserWallet> queryAllExistsLockedCoinWallet(String[] cointypes) throws BdexGatewayException {
        List<UserWallet> userWalletList = new ArrayList<>();
        for(String str: cointypes){
            List<UserWallet> userWalletList1 = userWalletMapper.queryAllExistsLockedCoinWallet(str);
            if(userWalletList1!=null && userWalletList1.size()>0){
                userWalletList.addAll(userWalletList1);
            }
        }
        return userWalletList;
    }

    @Override
    public void setBalanceOfReward() {

    }

}
